package com.fxc.mybatis.service.Impl;

import com.fxc.mybatis.entity.PageInfo;
import com.fxc.mybatis.entity.Stu;
import com.fxc.mybatis.mapper.StuMapper;
import com.fxc.mybatis.service.StuService;
import com.fxc.mybatis.util.PageHelper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

public class StuServiceImpl implements StuService {

    private StuMapper stuMapper;
    SqlSessionFactory sessionFactory;

    public StuServiceImpl() {
        InputStream inputStream = getClass().getResourceAsStream("/mybatis-config.xml");
        sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    }

    @Override
    public PageInfo<Stu> getPageInfo(int currentPage, int pageNum) throws Exception {
       SqlSession session = sessionFactory.openSession();
        stuMapper = session.getMapper(StuMapper.class);
        PageHelper<Stu> pageHelper = new PageHelper<>();
        pageHelper.startPage(currentPage,pageNum);
        List<Stu> stuList = stuMapper.queryAll();
        List<Stu> currentStus = stuMapper.queryByPage((currentPage - 1) * pageNum, pageNum);
        PageInfo<Stu> pageInfo = pageHelper.createPageInfo(stuList, currentStus);
        session.close();
        return pageInfo;
    }
}
